extends Node2D

@onready var player: Ark_Player = $Player
@onready var pointer_mark: PointerMark = $PointerMark
@onready var tile_map: TileMapLayer = $Map
@onready var fade_text: Label = $FadeText
@onready var bubble: TileMapLayer = $Bubble

@onready var option1: Sprite2D = $Option1
@onready var option2: Sprite2D = $Option2

@onready var curtain := $Curtain
var started: bool = false
const CURTAIN_OFF_TIME: float = 2.0

const SPAWN_POINT: Vector2 = Vector2(25, 110)
const FADE_IN_TIME: float = 1
const FADE_OUT_TIME: float = 1

const FADE_NONE = 0
const FADE_IN = 1
const FADE_IN_FIN = 2
const FADE_OUT = -1
const FADE_OUT_FIN = -2

var fade_state = FADE_NONE
var fade_elapsed = 0

var checked: bool = true
var cur_opt: int = 1

@onready var bubble_text = $Bubble/Text

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	BgmMgr.audioPlayer.stream = BgmMgr.bgm123
	BgmMgr.audioPlayer.play()
	player.position = SPAWN_POINT
	fade_text.modulate.a = 0
	pointer_mark.player_stopped.connect(show_text)
	bubble.enabled = false
	var tex_opt1 = preload("res://assets/textures/text/游戏内剧情文本/·挥挥手.png")
	var tex_opt2 = preload("res://assets/textures/text/游戏内剧情文本/·打招呼.png")

	option1.set_texture(tex_opt1)
	option2.set_texture(tex_opt2)
	
	option1.visible = false
	option2.visible = false
	select(1)
	
	bubble_text.visible = false
	
func show_options():
	option1.visible = true
	option2.visible = true
	
func hide_options():
	option1.visible = false
	option2.visible = false
	
func select(n: int) -> void:
	cur_opt = n
	if n == 1:
		option1.frame = 1
		option2.frame = 0
	elif n == 2:
		option1.frame = 0
		option2.frame = 1

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if not started:
		fade_elapsed += delta
		curtain.modulate.a = 1 - min(fade_elapsed, CURTAIN_OFF_TIME) / CURTAIN_OFF_TIME
		if curtain.modulate.a <= 0:
			fade_elapsed = 0
			started = true
		return
	
	if player.position.y > 257:
		player.position = SPAWN_POINT
	
	checked = Input.is_action_pressed("space")
	
	if fade_state == FADE_IN:
		if checked: # 空格跳过动画
			fade_text.modulate.a = 1
			fade_state = FADE_IN_FIN
			show_options()
			return
			
		fade_elapsed += delta
		fade_text.modulate.a = min(fade_elapsed, 1) / FADE_IN_TIME
		if fade_text.modulate.a >= 1:
			fade_state = FADE_IN_FIN
			show_options()
			return
			
	if fade_state == FADE_IN_FIN: # 动画结束才能做选择
		if Input.is_action_just_pressed("ui_left"):
			select(1)
		elif Input.is_action_just_pressed("ui_right"):
			select(2)
	
	if Input.is_action_just_pressed("space") and fade_state == 2 and cur_opt == 1:
		player.controllable = true
		bubble.enabled = true
		fade_text.visible = false
		hide_options()
		bubble_text.visible = true
		
	if player.position.x > 416:
		get_tree().change_scene_to_file("res://karte/karte_2.tscn")

func show_text() -> void:
	if fade_state == FADE_NONE:
		fade_state = FADE_IN

func hide_text() -> void:
	fade_state = FADE_OUT
